<template>
  <PageLayout title="消息系统测试" description="测试消息系统的各项功能">
      <div class="space-y-6">
        <!-- 测试消息创建 -->
        <div class="card">
          <h2 class="text-xl font-semibold text-text-primary mb-4">创建测试消息</h2>
          <div class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-text-primary mb-2">消息类型</label>
                <select v-model="testMessage.type" class="input w-full">
                  <option value="system">系统通知</option>
                  <option value="comment_reply">评论回复</option>
                  <option value="movie_upload">电影上传</option>
                  <option value="like">点赞通知</option>
                  <option value="follow">关注通知</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium text-text-primary mb-2">标题</label>
                <input v-model="testMessage.title" type="text" class="input w-full" placeholder="消息标题">
              </div>
            </div>
            <div>
              <label class="block text-sm font-medium text-text-primary mb-2">内容</label>
              <textarea v-model="testMessage.content" class="input w-full" rows="3" placeholder="消息内容"></textarea>
            </div>
            <div class="flex gap-2">
              <UiButton 
                variant="primary" 
                @click="createTestMessage"
                :loading="creating"
              >
                创建测试消息
              </UiButton>
              <UiButton 
                variant="secondary" 
                @click="createRandomMessage"
                :loading="creating"
              >
                创建随机消息
              </UiButton>
            </div>
          </div>
        </div>

        <!-- 消息统计 -->
        <div class="card">
          <h2 class="text-xl font-semibold text-text-primary mb-4">消息统计</h2>
          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div class="bg-background-800 p-4 rounded-lg">
              <div class="text-2xl font-bold text-primary">{{ unreadCount }}</div>
              <div class="text-sm text-text-secondary">未读消息</div>
            </div>
            <div class="bg-background-800 p-4 rounded-lg">
              <div class="text-2xl font-bold text-text-primary">{{ messages.length }}</div>
              <div class="text-sm text-text-secondary">总消息数</div>
            </div>
            <div class="bg-background-800 p-4 rounded-lg">
              <div class="text-2xl font-bold text-success">{{ readMessages.length }}</div>
              <div class="text-sm text-text-secondary">已读消息</div>
            </div>
          </div>
        </div>

        <!-- 最近消息列表 -->
        <div class="card">
          <div class="flex items-center justify-between mb-4">
            <h2 class="text-xl font-semibold text-text-primary">最近消息</h2>
            <div class="flex gap-2">
              <UiButton 
                variant="secondary" 
                size="sm"
                @click="refreshMessages"
                :loading="loading"
              >
                刷新
              </UiButton>
              <UiButton 
                variant="secondary" 
                size="sm"
                @click="markAllAsRead"
                :loading="markingAllAsRead"
                v-if="unreadCount > 0"
              >
                全部已读
              </UiButton>
            </div>
          </div>
          
          <div v-if="loading" class="flex justify-center py-8">
            <div class="text-text-muted">加载中...</div>
          </div>
          
          <div v-else-if="messages.length > 0" class="space-y-3">
            <div 
              v-for="message in messages.slice(0, 10)" 
              :key="message.id"
              class="p-4 bg-background-800 rounded-lg border border-gray-700"
            >
              <div class="flex items-start justify-between">
                <div class="flex-1">
                  <div class="flex items-center gap-2 mb-2">
                    <span class="font-medium text-text-primary">{{ message.title }}</span>
                    <span 
                      v-if="!message.is_read"
                      class="px-2 py-0.5 text-xs bg-primary text-white rounded-full"
                    >
                      未读
                    </span>
                    <span class="text-xs text-text-muted">{{ formatTime(message.created_at) }}</span>
                  </div>
                  <p class="text-sm text-text-secondary mb-2">{{ message.content }}</p>
                  <div class="flex items-center gap-4 text-xs text-text-muted">
                    <span>类型: {{ message.type }}</span>
                    <span v-if="message.sender_name">发送者: {{ message.sender_name }}</span>
                    <span v-if="message.related_movie_title">电影: {{ message.related_movie_title }}</span>
                  </div>
                </div>
                <div class="flex gap-2 ml-4">
                  <UiButton 
                    v-if="!message.is_read"
                    variant="ghost" 
                    size="sm"
                    @click="markAsRead(message.id)"
                  >
                    标记已读
                  </UiButton>
                  <UiButton 
                    variant="ghost" 
                    size="sm"
                    @click="deleteMessage(message.id)"
                  >
                    删除
                  </UiButton>
                </div>
              </div>
            </div>
          </div>
          
          <div v-else class="text-center py-8 text-text-muted">
            暂无消息
          </div>
        </div>
      </div>
  </PageLayout>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useMessages } from '../composables/useMessages'
import PageLayout from '../components/layout/PageLayout.vue'
import { UiButton } from '../components/ui'

// 使用消息composable
const {
  messages,
  unreadMessages,
  readMessages,
  unreadCount,
  loading,
  markAsRead,
  markAllAsRead,
  deleteMessage,
  createMessage,
  init
} = useMessages()

// 测试消息状态
const testMessage = ref({
  type: 'system' as any,
  title: '',
  content: ''
})
const creating = ref(false)
const markingAllAsRead = ref(false)

// 格式化时间
const formatTime = (dateString: string) => {
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN')
  } catch {
    return '未知时间'
  }
}

// 创建测试消息
const createTestMessage = async () => {
  if (!testMessage.value.title || !testMessage.value.content) {
    alert('请填写消息标题和内容')
    return
  }

  creating.value = true
  try {
    const result = await createMessage({
      recipient_id: 'current-user', // 这里应该使用当前用户ID
      type: testMessage.value.type,
      title: testMessage.value.title,
      content: testMessage.value.content
    })

    if (result.success) {
      alert('测试消息创建成功！')
      testMessage.value.title = ''
      testMessage.value.content = ''
      // 刷新消息列表
      await init()
    } else {
      alert(`创建失败: ${result.error}`)
    }
  } catch (error) {
    console.error('Error creating test message:', error)
    alert('创建测试消息失败')
  } finally {
    creating.value = false
  }
}

// 创建随机消息
const createRandomMessage = async () => {
  const randomMessages = [
    {
      type: 'system' as any,
      title: '系统维护通知',
      content: '系统将于今晚进行维护，预计持续2小时。'
    },
    {
      type: 'comment_reply' as any,
      title: '新回复',
      content: '用户回复了你的评论："这部电影真的很棒！"'
    },
    {
      type: 'movie_upload' as any,
      title: '电影上传成功',
      content: '恭喜！你的电影《测试电影》已成功上传并发布。'
    },
    {
      type: 'like' as any,
      title: '收到点赞',
      content: '用户点赞了你的评论。'
    },
    {
      type: 'follow' as any,
      title: '新关注者',
      content: '用户关注了你。'
    }
  ]

  const randomMessage = randomMessages[Math.floor(Math.random() * randomMessages.length)]
  testMessage.value = { ...randomMessage }

  await createTestMessage()
}

// 刷新消息
const refreshMessages = async () => {
  await init()
}

// 标记所有消息为已读
const handleMarkAllAsRead = async () => {
  markingAllAsRead.value = true
  try {
    await markAllAsRead()
  } finally {
    markingAllAsRead.value = false
  }
}

// 初始化
onMounted(() => {
  init()
})
</script>
